﻿using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Syngine.Components;
using Syngine.Content;

namespace Syngine.Controls
{
	public abstract class StateManager
	{
		#region Fields

		private readonly IDictionary<ControlState, Asset<Texture2D>> _textures = new Dictionary<ControlState, Asset<Texture2D>>();
		private readonly Drawable _drawable;

		private string _assetName;

		public const string DrawableAssetFormat = @"{0}\{1}";
		public const string ThemedControlAssetFormat = @"{0}\{1}\{2}";
		
		#endregion

		#region Constructors

		protected StateManager(Drawable drawable)
		{
			_drawable = drawable;
		}

		#endregion

		#region Properties

		/// <summary>
		/// The global default theme. Can be null.
		/// </summary>
		public static string DefaultTheme { get; set; }

		/// <summary>
		/// The default texture for the control.
		/// </summary>
		public Texture2D DefaultTexture { get; set; }

		public IDictionary<ControlState, Texture2D> Textures
		{
			get
			{
				return _textures;
			}
		}

		protected Drawable Drawable
		{
			get
			{
				return _drawable;
			}
		}

		#endregion

		#region Methods

		protected virtual void ApplyTheme(string theme, string assetName)
		{
			if (string.IsNullOrEmpty(theme))
			{
				_assetName = string.Format(DrawableAssetFormat, "Controls", assetName ?? Drawable.GetType().Name);
			}
			else
			{
				_assetName = string.Format(ThemedControlAssetFormat, "Controls", theme, assetName ?? Drawable.GetType().Name);
			}
		}

		public virtual void ApplyState(ControlState state)
		{
			Drawable.Texture = Textures.ContainsKey(state) ? Textures[state] : DefaultTexture;
		}

		public virtual void LoadTexture(LoadContext context, ControlState state)
		{
			if (state == ControlState.Default)
			{
				DefaultTexture = context.Load<Texture2D>(_assetName);
			}
			else
			{
				Textures[state] = context.Load<Texture2D>(string.Concat(_assetName, "_", state));
			}
		}

		#endregion
	}
}